<template>
    <div class="bg-gray-100 flex-1">
        <!-- 右侧内容区域 -->
        <div v-if="user.authenticationFlag !== '1'" class="flex p-4 items-center justify-center">
            <var-alert class="w-[40%]" type="warning" title="暂无权限访问" message="请先通过身份验证再访问该页面" />
        </div>
        <div v-if="user.authenticationFlag === '1'" class="flex-1 p-4">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-3xl font-semibold">科室患者</h2>
                <var-input v-model="searchText" variant="outlined" placeholder="搜索" focus-color="#006263" size="small" @change="handleSearch" />
            </div>
            <!-- 历史记录表格 -->
            <div class="bg-white p-2 rounded-lg shadow-md mx-auto">
                <var-tabs indicator-color="#006263" active-color="#006263" v-model:active="activeTab">
                    <var-tab>有效</var-tab>
                    <var-tab>已禁用</var-tab>
                </var-tabs>
                <div class="max-h-[528px] overflow-y-auto relative">
                    <table class="min-w-full">
                        <thead>
                            <tr>
                                <th v-for="header in headers" :key="header" class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">
                                    {{ header }}
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-if="listLoading">
                                <td colspan="7" class="px-6 py-1.4 text-center text-base text-gray-500">
                                    <var-loading description="LOADING" color="#006263" />
                                </td>
                            </tr>
                            <tr v-if="list.length === 0 && !listLoading">
                                <td colspan="7" class="px-6 py-1.4 text-center text-base text-gray-500">暂无数据</td>
                            </tr>
                            <tr v-for="(record, index) in list" :key="index" class="odd:bg-white even:bg-gray-50" v-hover="{ color: 'var(--color-on-primary)', background: '#F0F0F0' }">
                                <td class="px-6 py-1.5 text-center text-base text-gray-900">{{ record.name || '-' }}</td>
                                <td class="px-6 py-1.5 text-center text-base text-gray-900">{{ record.age || '-' }}</td>
                                <td class="px-6 py-1.5 text-center text-base text-gray-900">{{ record.sex || '-' }}</td>
                                <td class="px-6 py-1.5 text-center text-base text-gray-900">{{ record.creatorName || '-' }}</td>
                                <td class="px-6 py-1.5 text-center text-base text-gray-900">{{ formatDate(record.lastVisitDate) || '-' }}</td>
                                <td class="px-6 py-1.5 text-base">
                                    <div class="flex flex-col items-center justify-center">
                                        <var-space :size="[10, 10]">
                                            <var-button block color="#006263" text-color="white" @click="getRecord(record.patientId)" style="border-radius: 8px">查看</var-button>
                                        </var-space>
                                    </div>
                                </td>
                                <td class="px-6 py-1 text-base">
                                    <div class="flex flex-col items-center justify-center">
                                        <var-space :size="[10, 10]">
                                            <var-button block color="#006263" text-color="white" @click="viewRecord(record)" style="border-radius: 8px">编辑</var-button>
                                        </var-space>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <!-- 分页组件 -->
                <div class="flex justify-center mt-6">
                    <var-pagination v-model="currentPage" v-model:size="pageSize" :total="total" :size-option="[10, 20, 30]" :simple="true" @change="handlePageChange" style="color: #006263" />
                </div>
            </div>
        </div>
        <!-- 删除信息确认弹窗 -->
        <var-dialog v-model:show="showConfirm" title="删除提示" confirm-button-text-color="red" persistent cancel-button-text-color="#006263" width="35vw" @before-close="deleteUserpatient">
            <var-loading description="LOADING" color="red" :loading="deleteLoading">
                <div class="p-4">
                    <p class="text-lg text-gray-900">确认删除此用户？请谨慎操作！</p>
                </div>
            </var-loading>
        </var-dialog>
        <var-popup v-model:show="showRecordPopup" class="w-[25vw] h-[42vh] rounded-lg p-2">
            <div class=" max-h-[288px] flex justify-center items-center overflow-auto relative">
                <table class="min-w-full">
                    <thead>
                        <tr>
                            <th class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">就诊记录</th>
                            <th class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">查看</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-if="recordList.length === 0">
                            <td colspan="2" class="px-6 py-1.4 text-center text-base text-gray-500">暂无数据</td>
                        </tr>
                        <tr v-for="(record, index) in recordList" :key="index" class="odd:bg-white even:bg-gray-50" v-hover="{ color: 'var(--color-on-primary)', background: '#F0F0F0' }">
                            <td class="px-6 py-1.5 text-center text-base text-gray-900">{{ format(record.createdAt) }}</td>
                            <td class="px-6 py-1.5 text-base">
                                <div class="flex flex-col items-center justify-center">
                                    <var-space :size="[10, 10]">
                                        <var-button block color="#006263" text-color="white" @click="getRecordDetails(record.recordId)" style="border-radius: 8px">查看</var-button>
                                    </var-space>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </var-popup>
        <!--恢复信息确认弹窗  -->
        <var-dialog v-model:show="showRecoverConfirm" title="恢复提示" confirm-button-text-color="green" persistent cancel-button-text-color="#006263" width="35vw" @before-close="recoverUserpatient">
            <var-loading description="LOADING" color="green" :loading="recoverLoading">
                <div class="p-4">
                    <p class="text-lg text-gray-900">确认恢复此用户？请谨慎操作！</p>
                </div>
            </var-loading>
        </var-dialog>
        <!-- 居中弹窗 -->
        <var-popup v-model:show="showCenterPopup">
            <var-loading description="LOADING" color="#006263" :loading="loading">
                <div class="p-9 h-[430px] w-[500px] bg-white rounded-lg shadow-lg">
                    <!-- 弹窗内容 -->
                    <h3 class="text-lg font-semibold mb-2">{{ selectedRecord.name }}的个人信息</h3>
                    <div class="grid grid-cols-5 gap-8">
                        <!--左边列-->
                    </div>
                    <!--姓名-->
                    <div class="mb-4">
                        <var-input label="姓名" focus-color="#006263" v-model="updateUserpatient.name" placeholder="请输入修改后的姓名" variant="outlined" :rules="nameRules" />
                    </div>
                    <!--性别-->
                    <div class="mb-4">
                        <var-select label="性别" v-model="updateUserpatient.sex" placeholder="请选择性别" focus-color="#006263" variant="outlined">
                            <var-option v-for="option in sexOpition" :label="option.label" :value="option.value" />
                        </var-select>
                    </div>
                    <!--联系方式-->
                    <div class="mb-4">
                        <var-input label="联系方式" v-model="updateUserpatient.phone" focus-color="#006263" placeholder="请输入电话号码" variant="outlined" :rules="numberRules" />
                    </div>
                    <!--右边-->
                    <div>
                        <!-- 年龄 -->
                        <div class="mb-4">
                            <var-input label="年龄" v-model="updateUserpatient.age" focus-color="#006263" placeholder="请输入年龄" variant="outlined" :rules="ageRules" />
                        </div>
                    </div>
                    <!-- 按钮容器 -->
                    <div class="mt-auto flex justify-center">
                        <var-space :size="[10, 30]">
                            <var-button v-if="selectedRecord.validFlag === '1'" type="danger" @click="showConfirm = true">删除用户</var-button>
                            <var-button v-if="selectedRecord.validFlag === '0'" type="success" @click="showRecoverConfirm = true">恢复用户</var-button>
                            <var-button block color="#006263" text-color="white" @click="updatePatientInfo">保存修改</var-button>
                        </var-space>
                    </div>
                </div>
            </var-loading>
        </var-popup>
    </div>
</template>

<script>
import dayjs from 'dayjs';
export default {
    name: 'managerUser',
    data() {
        return {
            headers: ['姓名', '年龄', '性别', '创建人', '最后就诊时间', '就诊记录', '操作'],
            sexOpition: [
                { label: '男', value: 'MAN' },
                { label: '女', value: 'WOMAN' }
            ],
            list: [],
            recordList: [],
            showRecordPopup: false,
            searchText: '',
            listLoading: false, // 列表加载状态
            currentPage: 1, // 当前页码
            pageSize: 10, // 每页显示的记录数
            showCenterPopup: false, // 控制弹窗显示
            selectedRecord: {}, // 当前选中的记录
            activeTab: 0,
            updateUserpatient: {},
            loading: false,
            total: 0,
            showConfirm: false,
            showRecoverConfirm: false,
            recoverLoading: false,
            deleteLoading: false
        };
    },
    mounted() {
        if (this.user.authenticationFlag === '1') {
            this.getMyPatient();
        }
    },
    watch: {
        activeTab(newVal, oldVal) {
            if (newVal !== oldVal && this.searchText.trim() === '') {
                this.currentPage = 1;
                this.getMyPatient();
            }
            if (newVal !== oldVal && this.searchText.trim() !== '') {
                this.currentPage = 1;
                this.getMyPatientSearch();
            }
        }
    },
    computed: {
        user() {
            return this.$store.user;
        },
        nameRules() {
            return [
                (v) => /^[\u4e00-\u9fa5]{2,}$/.test(v) || '姓名必须为至少两个汉字！' // 使用正则表达式检查是否为汉字
            ];
        },
        numberRules() {
            return [
                (v) => /^\d{11}$/.test(v) || '输入的电话号码无效！' // 使用正则表达式检查是否为11位数字
            ];
        },
        ageRules() {
            return [(v) => (!isNaN(v) && v >= 1 && v <= 120) || '年龄必须是1到100之间的数字'];
        }
    },
    methods: {
        async handleSearch() {
            if (this.searchText.trim() === '') {
                await this.getMyPatient();
                return;
            }
            this.currentPage = 1;
            this.getMyPatientSearch();
        },
        async getMyPatientSearch() {
            const typeMap = [1, 0];
            const type = typeMap[this.activeTab];
            this.list = [];
            this.listLoading = true;
            const res = await this.$api.patient.searchPatients({ pageNum: this.currentPage, pageSize: this.pageSize, keyword: this.searchText, type: type });
            this.listLoading = false;
            if (res.success) {
                this.list = res.data.list; // 提取数组字段
                this.total = res.data.total; // 提取总记录数
            } else {
                this.$api.notify.error(res.error);
                this.list = [];
                this.total = 0;
            }
        },
        // 查看记录
        viewRecord(record) {
            this.updateUserpatient = { ...record };
            this.selectedRecord = record;
            this.showCenterPopup = true;
        },
        // 获取患者记录
        async getRecord(patientId) {
            const res = await this.$api.record.getRecordHistory({ patientId });
            if (res.success) {
                this.recordList = res.data;
                this.showRecordPopup = true;
            } else {
                this.$api.notify.error(res.error);
            }
        },
        // 获取患者记录详情
        async getRecordDetails(recordId) {
        this.$router.push({ name: 'recordDetails', params:{ recordId } });
        },
        //日期正常函数
        formatDate(date) {
            if (date == null) {
                return '';
            }
            return dayjs(date).format('YYYY年MM月DD日 HH:mm:ss');
        },
        format(date) {
            return dayjs(date).format('YYYY-MM-DD-HH-mm-ss');
        },
        //用户获取我的患者信息接口
        async getMyPatient() {
            this.list = [];
            const typeMap = [1, 0];
            const type = typeMap[this.activeTab];
            this.listLoading = true;
            const res = await this.$api.patient.getMyPatient({ pageNum: this.currentPage, pageSize: this.pageSize, type: type });
            this.listLoading = false;
            if (res.success) {
                this.list = res.data.list; // 提取数组字段
                this.total = res.data.total; // 提取总记录数
            } else {
                this.list = [];
                this.total = 0;
            }
        },
        //医生或者科研人员修改病人信息接口
        async updatePatientInfo() {
            const change = {};
            for (const key in this.updateUserpatient) {
                if (this.updateUserpatient[key] !== this.selectedRecord[key]) {
                    change[key] = this.updateUserpatient[key];
                }
            }
            if (Object.keys(change).length === 0) {
                this.$api.notify.warning('未做任何修改');
                return;
            }
            change.patientId = this.selectedRecord.patientId;
            change.departmentId = this.selectedRecord.departmentId;
            this.loading = true;
            const res = await this.$api.patient.updatePatientInfo(change);
            this.loading = false;
            if (res.success) {
                await this.getMyPatient();
                this.$api.notify.success('修改成功');
                this.showCenterPopup = false;
            } else {
                this.$api.notify.error(res.error);
            }
        },
        async deleteUserpatient(action, done) {
            if (action === 'confirm') {
                this.deleteLoading = true;
                const res = await this.$api.patient.updatePatientInfo({
                    patientId: this.selectedRecord.patientId,
                    departmentId: this.selectedRecord.departmentId,
                    validFlag: 0
                });
                this.deleteLoading = false;
                if (res.success) {
                    this.$api.notify.success('此用户已删除');
                    this.showConfirm = false;
                    this.showCenterPopup = false;
                    await this.getMyPatient();
                } else {
                    this.showConfirm = false;
                    this.$api.notify.error(res.error);
                }
            }
            done();
        },
        async recoverUserpatient(action, done) {
            if (action === 'confirm') {
                this.recoverLoading = true;
                const res = await this.$api.patient.updatePatientInfo({
                    patientId: this.selectedRecord.patientId,
                    departmentId: this.selectedRecord.departmentId,
                    validFlag: 1
                });
                this.recoverLoading = false;
                if (res.success) {
                    this.$api.notify.success('此用户已恢复');
                    this.showRecoverConfirm = false;
                    this.showCenterPopup = false;
                    await this.getMyPatient();
                } else {
                    this.showRecoverConfirm = false;
                    this.$api.notify.error(res.error);
                }
            }
            done();
        },
        // 处理分页变化
        handlePageChange(page, pageSize) {
            if (this.searchText.trim() === '') {
                if (this.currentPage !== page) {
                    this.currentPage = page;
                    this.getMyPatient();
                }
                if (this.pageSize !== pageSize) {
                    this.pageSize = pageSize;
                    this.currentPage = 1; // 切换分页大小时重置到第一页
                    this.getMyPatient();
                }
            } else {
                if (page !== this.currentPage) {
                    this.currentPage = page;
                    this.getMyPatientSearch();
                }
                if (this.pageSize !== pageSize) {
                    this.pageSize = pageSize;
                    this.currentPage = 1; // 切换分页大小时重置到第一页
                    this.getMyPatientSearch();
                }
            }
        }
    }
};
</script>

<style scoped></style>
